//
//  UIApplication+Ext.swift
//  TTCOM-iOS
//
//  Created by Toj on 10/20/22.
//

import UIKit

public extension UIApplication {
    
    var app_isActive: Bool {
        
        return applicationState == .active
    }
    
    /// 安全区Insets
    var app_safeAreaInsets: UIEdgeInsets {
        guard #available(iOS 11.0, *) else { return .zero }
        
        guard #available(iOS 13.0, *) else {
            let insets = keyWindow?.safeAreaInsets ?? .zero
            return insets
        }
        
        let windowScene = connectedScenes.first as? UIWindowScene
        let insets = windowScene?.windows.first?.safeAreaInsets ?? .zero
        return insets
    }
}

public extension UIApplication.State {
    
    var apps_isActive: Bool {
        return self == .active
    }
}

public extension UIApplication {
    
    var app_orientation: UIInterfaceOrientation {
        guard #available(iOS 13.0, *) else {
            return statusBarOrientation
        }
        let windowScene = connectedScenes.first as? UIWindowScene
        let orientation = windowScene?.interfaceOrientation
        return orientation ?? .portrait
    }
    
    func app_setOrientationPortrait(viewController: UIViewController? = nil) {
        app_setOrientation(interfaceMask: .portrait, viewController: viewController)
    }
    
    func app_setOrientationLandscape(viewController: UIViewController? = nil) {
        app_setOrientation(interfaceMask: .landscape, viewController: viewController)
    }
    
    func app_rotationToDeviceOrientation(viewController: UIViewController?) {
        UIViewController.attemptRotationToDeviceOrientation()
        
        guard #available(iOS 16.0, *) else { return }
        // 更新屏幕边缘
        viewController?.navigationController?.setNeedsUpdateOfScreenEdgesDeferringSystemGestures()
        viewController?.setNeedsUpdateOfScreenEdgesDeferringSystemGestures()
        viewController?.navigationController?.setNeedsUpdateOfSupportedInterfaceOrientations()
        viewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
    }
    
    func app_setOrientation(interfaceMask orientationMask: UIInterfaceOrientationMask, viewController: UIViewController? = nil) {
        guard #available(iOS 16.0, *) else {
            UIDevice.current.setValue(orientationMask.iom_toInterfaceOrientation.rawValue, forKey: "orientation")
            UIViewController.attemptRotationToDeviceOrientation()
            return
        }
        UIViewController.attemptRotationToDeviceOrientation()
        // 更新屏幕边缘
        viewController?.navigationController?.setNeedsUpdateOfScreenEdgesDeferringSystemGestures()
        viewController?.setNeedsUpdateOfScreenEdgesDeferringSystemGestures()
        viewController?.navigationController?.setNeedsUpdateOfSupportedInterfaceOrientations()
        viewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
        
        let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
        let geometryPreferences = UIWindowScene.GeometryPreferences.iOS(interfaceOrientations: orientationMask)
        windowScene?.requestGeometryUpdate(geometryPreferences, errorHandler: { error in
            print("-->toj: error:\(error.localizedDescription)")
        })
    }
    
    func app_setOrientation(device dorientation: UIDeviceOrientation, viewController: UIViewController? = nil) {
        app_setOrientation(interface: dorientation.do_toInterfaceOrientation, viewController: viewController)
    }
    
    func app_setOrientation(interface iorientation: UIInterfaceOrientation, viewController: UIViewController? = nil) {
        guard #available(iOS 16.0, *) else {
            UIDevice.current.setValue(iorientation.rawValue, forKey: "orientation")
            UIViewController.attemptRotationToDeviceOrientation()
            return
        }
        UIViewController.attemptRotationToDeviceOrientation()
        // 更新屏幕边缘
        viewController?.setNeedsUpdateOfScreenEdgesDeferringSystemGestures()
        viewController?.navigationController?.setNeedsUpdateOfScreenEdgesDeferringSystemGestures()
        
        viewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
        viewController?.navigationController?.setNeedsUpdateOfSupportedInterfaceOrientations()
        
        let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
        let geometryPreferences = UIWindowScene.GeometryPreferences.iOS(interfaceOrientations: iorientation.io_toMask)
        windowScene?.requestGeometryUpdate(geometryPreferences, errorHandler: { error in
            print("-->toj: error:\(error.localizedDescription)")
        })
    }
}


public extension UIInterfaceOrientation {
    
    var io_string: String {
        return isLandscape ? "landscape" : "portrait"
    }
    
    var io_toMask: UIInterfaceOrientationMask {
        switch self {
        case .landscapeLeft:
            return .landscapeLeft
        case .landscapeRight:
            return .landscapeRight
        default:
            return .portrait
        }
    }
}

public extension UIInterfaceOrientationMask {
    
    var iom_toInterfaceOrientation: UIInterfaceOrientation {
        switch self {
        case .landscapeLeft:
            return .landscapeLeft
        case .landscapeRight, .landscape:
            return .landscapeRight
        default:
            return .portrait
        }
    }
}
